package org.jma.app.ewisdom.services.utils;

import org.jma.app.ewisdom.entities.FileDescriptor;

import java.io.*;

/**
 * Joins all the FilePart elements of a FileDescriptor and rebuilds the physical File
 * @author jesmari@ono.com
 * @version 1.0
 * @since 1.0
 */
public class FileJoiner extends Thread{
        private String folderDest;
        private FileDescriptor fileDescriptor;
        private final int BUFFER_SIZE = 1024;
        private String version;

        /**
         * FileJoiner Constructor
         * @param folderDest destination folder to store the file
         * @param fileDescriptor FileDescriptor, contains the FilePart array
         * @param version name of the version to rebuid, must be "ver_x"
         */
        public FileJoiner (String folderDest,FileDescriptor fileDescriptor,String version)
        {
            this.folderDest = folderDest;
            this.fileDescriptor = fileDescriptor;
            this.version=version;
        }

        public void run () {
        	try {
            FileOutputStream fw=new FileOutputStream(folderDest+ File.separator + fileDescriptor.getFileName());
            for (int j=0;j<fileDescriptor.getFileParts("ver_"+version).length;j++){
            
                File file = new File(folderDest + File.separator +fileDescriptor.getFileName()+"_"+version+ "." + j + ".part");
                FileInputStream fileInputStream = new FileInputStream(file);
                byte[] buffer = new byte[BUFFER_SIZE];
                int bytesLeidos = 0;
                while ((bytesLeidos = fileInputStream.read(buffer, 0, BUFFER_SIZE)) != -1) {
                    fw.write(buffer, 0, bytesLeidos );
                }
                fileInputStream.close();
            }
            fw.close();
        	}catch (IOException ioe){
        		ioe.printStackTrace();
        	}

        }

}
